<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="日期时间" prop="dutyDate">
        <el-date-picker clearable v-model="queryParams.dutyDate" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['plan:duty:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['plan:duty:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['plan:duty:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dutyList" @selection-change="handleSelectionChange"
      :span-method="mergeCellsMethod">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="dutyId" /> -->
      <el-table-column label="日期" align="center" prop="dutyDate" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.dutyDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目" align="center" prop="projectName" width="180" />
      <el-table-column label="人员" align="center" prop="userName" />
      <el-table-column label="模块" align="center" prop="moduleName" />
      <el-table-column label="任务名称" align="center" prop="taskName" />

      <el-table-column label="耗时" align="center" prop="useTime" />
      <el-table-column label="详细信息" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['plan:duty:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['plan:duty:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改日报任务对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="dutyRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="日期时间" prop="dutyDate">
          <el-date-picker clearable v-model="form.dutyDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="人员选择" prop="assignUserId">
          <span style="width: 70%;">{{ form.userName }}</span>
          <el-button type="primary" icon="User" @click="handleOpenSelectUser">选择人员</el-button>
        </el-form-item>

        <el-form-item label="选择项目" prop="projectId">
          <el-select v-model="form.projectId" placeholder="请选择" clearable @change="handleProjectChange">
            <el-option v-for="item in projectList" :key="item.projectId" :label="item.projectName"
              :value="item.projectId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="项目模块" prop="module">
          <el-select v-model="form.moduleId" placeholder="请选择" clearable @change="handleModuleChange">
            <el-option v-for="item in moduleList" :key="item.moduleId" :label="item.moduleName" :value="item.moduleId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="任务" prop="module">
          <el-select v-model="form.taskId" placeholder="请选择" clearable>
            <el-option v-for="item in taskList" :key="item.taskId" :label="item.taskName" :value="item.taskId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="耗时" prop="useTime">
          <el-input v-model="form.useTime" placeholder="请输入耗时(天)" />
        </el-form-item>
        <el-form-item label="详细信息" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入详细信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选人dialog -->
    <el-dialog title="选择人员" v-model="userOpen" width="500px" append-to-body>
      <el-table :data="userList" @row-click="handleSelectUser">
        <el-table-column label="id" align="center" prop="userId" />
        <el-table-column label="部门" align="center" prop="dept.deptName" />
        <el-table-column label="姓名" align="center" prop="nickName" />
      </el-table>
      <pagination v-show="user_total > 0" :total="user_total" v-model:page="userQueryParams.pageNum"
        v-model:limit="userQueryParams.pageSize" @pagination="getUserList" />
    </el-dialog>

  </div>
</template>

<script setup name="Duty">
import { listDuty, getDuty, delDuty, addDuty, updateDuty } from "@/api/task/duty";
import { listInfo } from "@/api/task/info";
import { listModule } from "@/api/task/module";
import { listProjectInfo } from "@/api/task/project";
import { listUser } from "@/api/system/user";

const { proxy } = getCurrentInstance();

const dutyList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");


//项目
const projectList = ref([]);
//模块
const moduleList = ref([]);
//任务
const taskList = ref([]);


// 选择用户 user_total
const userList = ref([]);
const user_total = ref(0);
const userOpen = ref(false);
const userQueryParams = ref({
  pageNum: 1,
  pageSize: 10,
});

const data = reactive({
  form: {
    dutyId: null,
    dutyDate: null,
    projectId: null,
    projectName: "",
    moduleId: null,
    moudleName: "",
    taskId: null,
    taskName: "",
    userId: null,
    userName: "",
    remark: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    delFlag: null,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dutyDate: null,
    taskId: null,
    moduleId: null,
    userId: null,
  },
  rules: {
    dutyDate: [
      { required: true, message: "请选择日期", trigger: "blur" },
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询日报任务列表 */
function getList() {
  loading.value = true;
  listDuty(queryParams.value).then(response => {
    dutyList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    dutyId: null,
    date: null,
    projectId: null,
    moduleId: null,
    taskId: null,
    userId: null,
    remark: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    delFlag: null
  };
  proxy.resetForm("dutyRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.dutyId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加日报任务";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _dutyId = row.dutyId || ids.value
  getDuty(_dutyId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改日报任务";

    //获取模块
    getModuleList(form.value.projectId);
    //获取任务
    getTaskList(form.value.moduleId);
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["dutyRef"].validate(valid => {
    if (valid) {
      if (form.value.dutyId != null) {
        updateDuty(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDuty(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _dutyIds = row.dutyId || ids.value;
  proxy.$modal.confirm('是否确认删除日报任务编号为"' + _dutyIds + '"的数据项？').then(function () {
    return delDuty(_dutyIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('plan/duty/export', {
    ...queryParams.value
  }, `duty_${new Date().getTime()}.xlsx`)
}

//==========================================================
/** 查询用户列表 */
function getUserList() {
  listUser(proxy.addDateRange(userQueryParams.value)).then(res => {
    userList.value = res.rows;
    user_total.value = res.total;
  });
};

function handleOpenSelectUser() {
  userOpen.value = true;
  getUserList();
};


function handleSelectUser(row) {
  userOpen.value = false;
  form.value.userId = row.userId;
  form.value.userName = row.nickName;
};


//==========================================================
//项目选择
function getProjectList() {
  let projectQueryParams = {
    pageNum: 1,
    pageSize: 100,
  };
  listProjectInfo(projectQueryParams.value).then(response => {
    projectList.value = response.rows;
    if (projectList.value.length == 0) {
      return;
    }
  });
}
//点击选择项目
function handleProjectChange(sel) {
  form.projectId = sel
  console.log(form.projectId);
  getModuleList(form.projectId);
}


//==========================================================
/** 查询项目模块列表 */
function getModuleList(projectId) {
  let queryParams = {
    pageNum: 1,
    pageSize: 100,
    projectId: projectId,
  }

  listModule(queryParams).then(response => {
    moduleList.value = response.rows;
  });
}

//点击选择项目
function handleModuleChange(sel) {
  form.moudleId = sel;
  console.log("====handleModuleChange " + form.moudleId);
  getTaskList(form.moudleId);
}

//==========================================================
/** 查询项目模块列表 */
function getTaskList(moudleId) {

  let queryParams = {
    pageNum: 1,
    pageSize: 100,
    moduleId: moudleId,
  }
  console.log("====getTaskList ", queryParams);
  listInfo(queryParams).then(response => {
    taskList.value = response.data;
  });
}

//===========================================================

function mergeCellsMethod({ row, column, rowIndex }) {
  // 根据行id进行合并，这样不会导致上下数据相同但id不同时会合并错误的问题
  switch (column.property) {
    case 'dutyDate':
      return setTableRowCol(row, rowIndex, ['dutyDate'])
    case 'projectName':
      return setTableRowCol(row, rowIndex, ["dutyDate", 'projectName'])
    default:
      break
  }
}
function setTableRowCol(row, rowIndex, keys) {
  let firstIndex = 0
  let rowspan = 1
  let colspan = 1
  // 找到需要合并的行的下标
  firstIndex = dutyList.value.findIndex((item) => {
    return filterSameKeys(item, row, keys)
  })
  if (rowIndex === firstIndex) {
    // 需要合并的行数
    rowspan = dutyList.value.filter((item) => {
      return filterSameKeys(item, row, keys)
    }).length
    colspan = 1
  } else {
    // 被合并的行需要设置成0
    rowspan = 0
    colspan = 0
  }
  return {
    rowspan,
    colspan
  }
}

// 根据keys数组所有字段去做合并
function filterSameKeys(item, row, keys) {
  let flag = true
  keys.forEach((key) => {
    flag = flag && item[key] === row[key]
  })
  return flag
}

//=============================================
getList();
//查项目
getProjectList();
</script>
